import {defineStore} from "pinia";
import {nextTick, reactive, ref} from "vue";
import type {Ref} from "vue";
import useAppStore from "./app.ts";
import {setToken, getToken} from "@/utils/token/token.ts";

interface UserState {
    token: string;
    userName: Ref<string | null>;
    themeColor: Ref<string>;
    getUserName: () => string | null;
    getThemeColor: () => string;
    setThemeColor: (color: string) => void;
    userInfo: UserInfo;
    setUserInfo: (info: UserInfo) => void;
    setUserToken: (token: string) => void;
    loginType: () => string;
}

interface UserInfo {
    id?: number;
    username?: string;
    password?: string;
    sex?: number;
    email?: string;
    birth?: string;
    introduction?: string;
    location?: string;
    avator?: string;
    state?: string;
    legality?: string;
    picurl?: string;
    vip?: string;
    phoneNum?: string;
    updateTime?: string;
    createTime?: string;
    theme?: string;
}

const useUserStore = defineStore("user", (): UserState => {
    const app = useAppStore();
    let userName = ref<string | null>(null);
    const getUserName = (): string | null => {
        return userName.value;
    };
    // theme
    let themeColor = ref<string>("#1890ff");
    const getThemeColor = (): string => {
        return themeColor.value;
    };
    const setThemeColor = (color: string): void => {
        app.setAppLoading(false);
        nextTick(() => {
            themeColor.value = color;
        });
        setTimeout(() => {
            app.setAppLoading(true);
        }, 100);
    };
    // token
    const token: string = getToken();
    const setUserToken = (token: string) => {
        setToken(token);
    };
    const userInfo = reactive<UserInfo>({});
    const setUserInfo = (info: UserInfo) => {
        userInfo.id = info.id;
        userInfo.username = info.username;
        userInfo.password = info.password;
        userInfo.sex = info.sex;
        userInfo.email = info.email;
        userInfo.birth = info.birth;
        userInfo.introduction = info.introduction;
        userInfo.location = info.location;
        userInfo.avator = info.avator;
        userInfo.state = info.state;
    };

    // 判断是pc端还是移动端
    const loginType = (): string => {
        const screenWidth = screen.width;
        return screenWidth > 768 ? "pc" : "mobile"; // 可根据需求调整阈值
    };
    return {
        token,
        userName,
        themeColor,
        userInfo,
        getUserName,
        getThemeColor,
        setThemeColor,
        setUserInfo,
        setUserToken,
        loginType,
    };
});
export default useUserStore;
